
#include "WSListener.h"
#include <cstddef>
#include <iostream>
#include "oatpp-websocket/WebSocket.hpp"
#include "oatpp-websocket/ConnectionHandler.hpp"
#include <iterator>
#include <map>
#include <string>
#include <vector>
#include "../Mysqlutil/test.h"
#include "string"
#include "../Mysqlutil/test.h"
// 定义一个锁对象
std::mutex listener_mutex;
student stu;
std::vector<std::string> msgs;

const std::string& WSListener::getId()
{
	int id = std::stoi(this->id);
	char condition[1024];
	 sprintf(condition, " WHERE stuId = %d ;",id );
    vector<Student> ret = StudentManager::GetInstance()->queryStu(condition);
    for (auto &it : ret) {
      std::cout << " ";
      cout << it.stuId << " " << it.stuName << " " << it.className;
	  stu = it;
    }
		return this->id;
}

WSListener::WSListener(std::string id, std::map<std::string, const WebSocket*>* conn_pool)
{
	this->id = id;
	this->conn_pool = conn_pool;
}

void WSListener::onPing(const WebSocket& socket, const oatpp::String& message)
{
	
	// OATPP_LOGD(TAG, "onPing");
	// #define OATPP_LOGE(TAG, onpii);
	socket.sendPong(message);
}

void WSListener::onPong(const WebSocket& socket, const oatpp::String& message)
{
	// OATPP_LOGD(TAG, "onPong");
}

void WSListener::onClose(const WebSocket& socket, v_uint16 code, const oatpp::String& message)
{
	// OATPP_LOGD(TAG, "onClose code=%d", code);
}

void WSListener::readMessage(const WebSocket& socket, v_uint8 opcode, p_char8 data, oatpp::v_io_size size)
{
	// message transfer finished
	if (size == 0)
	{

		// 获取消息数据
		auto wholeMessage = m_messageBuffer.toString().getValue("");
		m_messageBuffer.setCurrentPosition(0);
	
			 int start = 0;
    int end = wholeMessage.find("::");
    while (end!= std::string::npos) {
        msgs.push_back(wholeMessage.substr(start, end - start));
        start = end + 2;
		end = wholeMessage.find("::", start);
    }
    msgs.push_back(wholeMessage.substr(start));
		// 群发消息ID=all表示群发
  for (std::vector<std::string>::iterator it = msgs.begin(); it!= msgs.end(); it++) {
    if ("all" == *it )
		{
			it++;
			std::lock_guard<std::mutex> guard(listener_mutex);
			for (auto one : *conn_pool)
			{
				// 排除自己
				if (one.second == &socket)
				{
					continue;
				}
				// 发送消息
		
				one.second->sendOneFrameText(*it);
		
			}
		}
		// 指定发送
		else
		{
			std::lock_guard<std::mutex> guard(listener_mutex);
			auto iter = conn_pool->find(msgs[0]);
			if (iter != conn_pool->end())
			{
				iter->second->sendOneFrameText(*it);
			
			}
		}
		// socket.sendOneFrameText("message send success");
	}
    }
		
	// message frame received
	else if (size > v_int64(0))
	{
		m_messageBuffer.writeSimple(data, v_buff_size(size));
	}
}